var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
var xlsx = require('node-xlsx');
let { LoginModel,authenticationModel,operationModel,StandingModel,AuthorityModel,manageListModel, BusinessModel, DeliveryModel, BuyerModel, OrderModel, ProductModel, } = require('../model/model');
const Core = require("@alicloud/pop-core");
const CryptoJS = require('crypto-js');
const request = require('request')
const axios = require('axios');
const translate = require('@vitalets/google-translate-api');
//密码加密
const bcrypt = require('bcryptjs');
/* GET home page. */
const multiparty = require("multiparty");
var xlsx = require("node-xlsx");
/* GET home page. */
var Mock = require("mockjs");
var Random = Mock.Random;

//模拟配送员信息不能删!!!!
router.get("/data", async (req, res) => {
  let data = [];
  const banks = [
    "中国工商银行",
    "中国农业银行",
    "中国银行",
    "中国建设银行",
    "交通银行",
    "招商银行",
    "中信银行",
    "光大银行",
    "华夏银行",
    "广发银行",
    "平安银行",
    "浦发银行",
    "中国邮政储蓄银行",
  ]; //生成随机银行

  function generateRandomPhone() {
    const secondDigit = ["5", "3", "7", "8"][Math.floor(Math.random() * 4)]; // 随机选择5、3、7或8中的一个
    const remainingDigits = Math.floor(
      Math.random() * Math.pow(10, 9)
    ).toString(); // 生成9位随机数字
    const phone = `1${secondDigit}${remainingDigits.padStart(9, "0")}`; // 使用padStart确保剩余部分始终为9位
    return phone;
  }

  for (let i = 0; i < 10; i++) {
    data.push({
      basicInfo: {
        id: Random.integer(1, 99999), // 用户ID
        name: Random.cname(), // 姓名
        phone: generateRandomPhone(), // 手机号码
        email:
          generateRandomPhone() +
          ["@163.com", "@126.com"][Math.floor(Math.random() * 2)],

        jobType: ["全职专送", "兼职众包"][Math.floor(Math.random() * 2)], // 工作类型
        jobPlace: "保定市莲池区焦庄乡", // 工作地点
        completedOrders: Random.integer(0, 100), // 本月完成订单数
        score: Random.integer(1, 5, 1), // 评分
        authentication: Random.boolean(), // 认证状态
        registerTime: new Date(), // 注册时间
        status: ["未开通", "已开通", "接单中", "休息中", "已锁定", "已离职"][
          Math.floor(Math.random() * 6)
        ], // 接单状态
        lockStatus: Random.boolean(), // 锁定状态
        deposit: Random.integer(0, 1000), // 押金
        depositStatus: Random.boolean(), // 押金状态
        cloth: Random.boolean(), // 服装
        mealBox: Random.boolean(), // 餐箱
        traffic: ["电车", "摩托车", "三轮"][Math.floor(Math.random() * 3)], // 交通工具
        activationTime: new Date(), // 开通时间
        lastLoginTime: new Date(), // 最后登录时间
      },
      accountInfo: {
        balance: Random.integer(0, 10000), // 账户余额
        paymentPassword: Random.integer(1000, 9999), // 支付密码
        status: Random.boolean(), // 账户状态
      },
      authentication: {
        realName: Random.cname(), // 真实姓名
        idDocumentType: [
          "居民身份证",
          "台湾居民往来大陆通行证",
          "港澳居民往来大陆通行证",
        ][Math.floor(Math.random() * 3)], // 证件类型
        idNumber: Random.id(), // 证件号
        idCardFront: "", // 身份证正面照片 URL
        idCardBack: "", // 身份证反面照片 URL
        status: false, // 实名认证状态
      },
      bankInfo: {
        bankName: Math.floor(Math.random() * banks.length), // 银行名称
        accountNumber: "", // 银行卡号
        accountHolder: "", // 持卡人姓名
        bindingStatus: false, // 银行卡绑定状态
      },
    });
  }
  console.log(data);

  const savedData = await Promise.all(
    data.map((item) => new manageListModel(item).save())
  );
  res.json(savedData);
});
//获取配送员信息
router.get("/manage", async (req, res) => {
  let page = Number(req.query.currentPage);
  let pageSize = Number(req.query.pageSize);
  console.log(page);
  let total = await manageListModel.countDocuments();
  let working = await manageListModel.countDocuments({
    "basicInfo.status": "接单中",
  });
  console.log(working);

  let resting = await manageListModel.countDocuments({
    "basicInfo.status": "休息中",
  });
  let unavailable = await manageListModel.countDocuments({
    "basicInfo.status": "未开通",
  });

  let data = await manageListModel
    .find()
    .skip((page - 1) * pageSize)
    .limit(pageSize);
  // let data = await manageListModel.find();
  res.send({
    code: 200,
    data: data,
    total: total,
    working: working,
    resting: resting,
    unavailable: unavailable,
  });
});

//配送员搜索
router.post("/manage/search", async (req, res) => {
  let data = req.body;
  // console.log(data, "111111");
  // 动态构建查询条件
  const query = {};
  if (data.name) {
    query["basicInfo.name"] = { $regex: data.name, $options: "i" };
  }
  if (data.id) {
    query["basicInfo.id"] = data.id;
  }
  if (data.phone) {
    query["basicInfo.phone"] = { $regex: data.phone, $options: "i" };
  }
  if (data.jobType) {
    query["basicInfo.jobType"] = data.jobType;
  }
  if (data.score_min && data.score_max) {
    query["basicInfo.score"] = {
      $gte: parseFloat(data.score_min),
      $lte: parseFloat(data.score_max),
    };
  }
  if (data.registerTime) {
    const today = new Date(); // 获取当前时间
    let startDate, endDate;
    switch (data.registerTime) {
      case "全部":
        // 不限制日期范围
        break;
      case "本月内":
        startDate = new Date(today.getFullYear(), today.getMonth(), 1);
        endDate = new Date(today.getFullYear(), today.getMonth() + 1, 0);
        break;
      case "近三个月":
        startDate = new Date(today.getFullYear(), today.getMonth() - 3, 1);
        endDate = new Date(today.getFullYear(), today.getMonth() + 1, 0);
        break;
      case "今年内":
        startDate = new Date(today.getFullYear(), 0, 1);
        endDate = new Date(today.getFullYear(), 11, 31);
        break;
      case "2021年":
        startDate = new Date(2021, 0, 1);
        endDate = new Date(2021, 11, 31);
        break;
      case "2020年":
        startDate = new Date(2020, 0, 1);
        endDate = new Date(2020, 11, 31);
        break;
      case "2020年以前":
        endDate = new Date(2020, 0, 0);
        break;
      default:
        throw new Error("Invalid registerTime option");
    }

    if (startDate && endDate) {
      query["basicInfo.registerTime"] = {
        $gte: startDate,
        $lte: endDate,
      };
    } else if (endDate) {
      query["basicInfo.registerTime"] = {
        $lte: endDate,
      };
    }
  }

  const manageList = await manageListModel.find(query);

  // 如果没有找到数据
  if (manageList.length === 0) {
    return res.status(404).send({
      code: 404,
      message: "未找到匹配的数据",
    });
  }

  res.send({
    code: 200,
    data: manageList,
  });
});

// 配送员添加
router.post("/manage/addmanage", async (req, res) => {
  try {
    // 从请求体中提取数据
    const deliveryPersonData = req.body;
    // 生成唯一的用户ID
    let userId;
    do {
      userId = Random.integer(1, 99999); // 生成一个随机整数
    } while (await manageListModel.exists({ "basicInfo.id": userId })); // 检查ID是否已存在
    // 创建一个新的配送员对象
    const newDeliveryPerson = new manageListModel({
      basicInfo: {
        id: userId, // 用户ID
        name: deliveryPersonData.name, // 姓名
        phone: deliveryPersonData.phone, // 组合完整的电话号码
        // email: deliveryPersonData.email, // 邮箱
        jobType: deliveryPersonData.jobType, // 工作类型
        jobPlace: deliveryPersonData.jobPlace, // 工作地点
        // traffic: deliveryPersonData.traffic, // 交通工具
        intended_location: deliveryPersonData.intended_location, // 意向地点
      },
    });

    // 保存到数据库
    const savedDeliveryPerson = await newDeliveryPerson.save();

    // 返回结果
    res.send({ code: 200, data: savedDeliveryPerson });
  } catch (error) {
    console.error("Error adding delivery person:", error);
    res.status(500).send({ code: 500, message: "Internal server error" });
  }
});

//指派订单
router.get("/assignorder", async (req, res) => {

});

//register
router.post("/register", async (req, res) => {
  let { username, password } = req.body;
  let data = await LoginModel.findOne({ username }).lean();
  if (data) {
    res.send({ code: 500, msg: "用户名已存在" })
  } else {
    let newUser = new LoginModel({ username, password })
    let result = await newUser.save();
    res.send({ code: 200, msg: "注册成功", data: result })
  }
})

//login  账号密码版本（无手机验证码）
router.post("/login", async (req, res) => {
  let { username, password ,mobile} = req.body;
  const user=await LoginModel.findOne({ mobile }).lean().populate('standing').select('+password');

  try {
    // 如果用户不存在
    if (!user) {
      return res.status(401).send({ code: 501, msg: "用户名不存在" });
    }

    // 比较密码
    // let isMatch = bcrypt.compare(password, user.password);
    if (password!=user.password) {
      return res.status(402).send({ code: 502, msg: "密码错误" });
    }

    // 生成JWT Token
    let accessToken = jwt.sign({ id: user._id, auth: user.auth }, "jwtSecret", { expiresIn: "1h" });

    // 生成第二个Token，这里使用密码散列作为示例
    let secondToken = jwt.sign({ passwordHash: user.password }, "anotherSecret", { expiresIn: "1d" });

    res.send({
      code: 200,
      msg: "登录成功",
      accessToken,
      secondToken,
      username,
      user
    });
  } catch (error) {
    res.status(500).send({ msg: "服务器错误", error: error.message });
    console.log(error);
    
  }
});

// 加密函数
function encrypt(word, keyStr, ivStr){
    keyStr = keyStr ? keyStr : "abcdefgabcdefg12";
    ivStr = ivStr ? ivStr : "!@#$%asdfg12345";
    let key = CryptoJS.enc.Utf8.parse(keyStr);
    let iv = CryptoJS.enc.Utf8.parse(ivStr);
    let srcs = CryptoJS.enc.Utf8.parse(word);
    let encrypted = CryptoJS.AES.encrypt(srcs, key, {
        iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding
    })
    return encrypted.toString()
}

// 解密函数
function decrypt(word, keyStr, ivStr) {
    word = (word + '').replace(/\n*$/g, '').replace(/\n/g, ''); //增加这一行，将换行符替换为空
    keyStr = keyStr ? keyStr : "abcdefgabcdefg12";
    ivStr = ivStr ? ivStr : "!@#$%asdfg12345";
    var key = CryptoJS.enc.Utf8.parse(keyStr);
    let iv = CryptoJS.enc.Utf8.parse(ivStr);
    var decrypt = CryptoJS.AES.decrypt(word, key, {
        iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding
    })
    return decrypt.toString(CryptoJS.enc.Utf8)
}

//添加账号，子账号
router.post("/adduser",async(req,res)=>{
    // 秘文长度
    const hashLen = 10
    const encipherPassword = bcrypt.hashSync(req.body.password, hashLen)
    req.body.password=encipherPassword
    req.body.newTime=new Date()
    req.body.loginTime=new Date()
    await LoginModel.create(req.body)
    res.send({code:200})
})
router.get("/getuser",async(req,res)=>{
    let {_id,username,standing,status}=req.query
    let userList=[]
    let userReg=new RegExp(username)
    if(username && standing && status){
        let list=await LoginModel.find({$and:[{username:userReg},{standing},{status}]})
        let item=list.map(result=>result.standing)
        userList=await LoginModel.aggregate([
            {
                $match:{standing:{$in:item}}
            },
            {
                $lookup:{
                    from:'standing',
                    localField:'standing',
                    foreignField:'_id',
                    as:'standing'
                }
            }
        ])
    }else if(username && standing){
        let list=await LoginModel.find({$and:[{username:userReg},{standing}]})
        let item=list.map(result=>result.standing)
        userList=await LoginModel.aggregate([
            {
                $match:{standing:{$in:item}}
            },
            {
                $lookup:{
                    from:'standing',
                    localField:'standing',
                    foreignField:'_id',
                    as:'standing'
                }
            }
        ])
    }else if(username && status){
        let list=await LoginModel.find({$and:[{username:userReg},{status}]})
        let item=list.map(result=>result.standing)
        userList=await LoginModel.aggregate([
            {
                $match:{standing:{$in:item}}
            },
            {
                $lookup:{
                    from:'standing',
                    localField:'standing',
                    foreignField:'_id',
                    as:'standing'
                }
            }
        ])
    }else if(standing && status){
        let list=await LoginModel.find({$and:[{standing},{status}]})
        let item=list.map(result=>result.standing)
        userList=await LoginModel.aggregate([
            {
                $match:{standing:{$in:item}}
            },
            {
                $lookup:{
                    from:'standing',
                    localField:'standing',
                    foreignField:'_id',
                    as:'standing'
                }
            }
        ])
    }else if(username){
        let list=await LoginModel.find({username:userReg})
        let item=list.map(result=>result.standing)
        userList=await LoginModel.aggregate([
            {
                $match:{standing:{$in:item}}
            },
            {
                $lookup:{
                    from:'standing',
                    localField:'standing',
                    foreignField:'_id',
                    as:'standing'
                }
            }
        ])
    }else if(standing){
        let list=await LoginModel.find({standing})
        let item=list.map(result=>result.standing)
        userList=await LoginModel.aggregate([
            {
                $match:{standing:{$in:item}}
            },
            {
                $lookup:{
                    from:'standing',
                    localField:'standing',
                    foreignField:'_id',
                    as:'standing'
                }
            }
        ])
    }else if(status){
        let list=await LoginModel.find({status})
        let item=list.map(result=>result.standing)
        userList=await LoginModel.aggregate([
            {
                $match:{standing:{$in:item}}
            },
            {
                $lookup:{
                    from:'standing',
                    localField:'standing',
                    foreignField:'_id',
                    as:'standing'
                }
            }
        ])
    }else if(_id){
        userList=await LoginModel.find({_id})
    }else{
        userList=await LoginModel.aggregate([
            {
                $lookup:{
                    from:'standing',
                    localField:'standing',
                    foreignField:'_id',
                    as:'standing'
                }
            }
        ])
    }
    res.send({userList})
})
router.delete('/deluser/:_id',async(req,res)=>{
    let _id=req.params._id
    await LoginModel.deleteOne({_id})
    res.send({code:200})
})
router.put('/edituser/:_id',async(req,res)=>{
    let _id=req.params._id
    await LoginModel.findByIdAndUpdate(_id,req.body)
    res.send({code:200})
})
router.put('/editusermore/:ids',async(req,res)=>{
    let ids=req.params.ids.split(',');
    let updateContent=req.body
    await LoginModel.updateMany(
        { _id: { $in: ids } },
        { $set: { status: req.body.status } }
    )
    res.send({code:200})
})


//图片上传
router.post("/uploadImg", (req, res) => {
    let form = new mutiparty.Form()
    form.uploadDir = "upload"
    form.parse(req, (err, a, imgData) => {
        res.send({
            imgPath: "http://localhost:3001/" + imgData.file[0].path
        })
    })
})

//获取验证码
//cwen 对阿里短信服务API进行配置
let client = new Core({
    accessKeyId: 'LTAI5t9SFKYc7YKxnuspM1fs',
    accessKeySecret: 'yNixQ8Vj3kEVBoInxmplrg83WbgxPi',
    endpoint: 'https://dysmsapi.aliyuncs.com',
    apiVersion: '2017-05-25'
});
//cwen 请求方式
let requestOption = {
  method: 'POST'
};

//# 生成随机四位数，模拟验证码
function rander(max, min) {
  return Math.floor(Math.random() * (max - min)) + min
}
//# 存储手机号+验证码（方便验证）
var loginInfo = [];
//# 验证手机号是否已经发送验证码
let validate = (phone) => {
  return loginInfo.some(item => item.mobile === phone)
}
//# 验证验证码是否一致
let validateCode = (mobile, captcha) => {
  return loginInfo.some(item => (item.mobile === mobile && item.captcha == captcha))
}
//cwen 用阿里云api发送短信验证(验证码登录)
router.post("/sendCroeCode",async(req,res) => {
    let { mobile } = req.body;
    let randCode = rander(100000, 999999);
    var params = {
      PhoneNumbers: mobile, // 客户端手机号
      SignName: "美食外卖配送站后台系统", //签名
      TemplateCode: "SMS_467610230", //模板，用于发送文字信息
      TemplateParam: JSON.stringify({ 'code': randCode }) //指定要发送的验证码（此处以rander 函数为例）
    }
    client.request('SendSms', params, requestOption).then((result) => {
        if (result.Code == 'OK') {
            res.send({
                status: 200,
                msg: '发送成功',
                captcha:randCode
            });
            loginInfo.push({
                mobile: mobile,
                captcha: randCode
            });
        } else {
            res.send({
                status: 400,
                msg: '发送失败'
            })
        }
    })
})

router.post("/nextCode",async(req,res)=>{
    let {mobile,captcha}=req.body
    if (validateCode(mobile, captcha)){
        res.send({
            code:200
        })
    }else{
        res.send({
            code:201,
            msg:'验证码错误'
        })
    }
})

//更换手机号
router.put('/editMobile',async(req,res)=>{
    let { mobile,phone } = req.body;
    let user = await LoginModel.findOne( { mobile: phone } )
    await LoginModel.updateOne({ _id:user._id },{ $set:{ mobile:mobile } } )
    res.send( {
      code: 200
    })
})



//实名认证
router.post('/addPeople',async(req,res)=>{
    // let {idNumber}=req.body
    req.body.idNumber=encrypt(req.body.idNumber)
    await authenticationModel.create(req.body)
    res.send({
        code:200,
        msg:'认证成功'
    })
})
router.get('/getPeople',async(req,res)=>{
    let {_id}=req.query
    let peopleList=await authenticationModel.find({_id})
    res.send({peopleList})
})



//获取access_token
function getAccessToken() {
    const clientId = "rQEYkKmxfNXayQhi7GbqNq3S"
    const clientSecret = "x11Nybrtb6qwrbDE0o5lLwEX2dNd6GfR"
    let options = {
        'method': 'POST',
        'url': 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + clientId + '&client_secret=' + clientSecret,
    }
    return new Promise((resolve, reject) => {
        request(options, (error, response) => {
            if (error) { reject(error) }
            else { resolve(JSON.parse(response.body).access_token) }
        })
    })
}
//识别身份证正面文字
router.get('/rest/ocr',async(req,res)=>{
    let {frontImg}=req.query
    var options = {
        'method': 'POST',
        'url': 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' + await getAccessToken(),
        'headers': {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        },
        form: {
                'id_card_side': 'front',
                'image': frontImg,
                //是否检测上传的身份证被PS
                'detect_ps': 'false',
                //是否开启身份证风险类型
                'detect_risk': 'false',
                //是否开启身份证质量类型
                'detect_quality': 'true',
                'detect_photo': 'false',
                //是否检测身份证进行裁剪
                'detect_card': 'false',
                //是否检测上传的身份证图片方向
                'detect_direction': 'true'
            }
    };

    request(options, function (error, response) {
        if (error) throw new Error(error);
        console.log(response.body);
        
        res.send({
            value:response.body
        })
    });
})


// 获取服务器的公共 IP 地址
async function getPublicIP() {
  try {
    const response = await axios.get('https://ifconfig.me');
    return response.data;
  } catch (error) {
    console.error('Error fetching public IP:', error.message);
    return null;
  }
}

// 获取 IP 归属地
async function getIPGeoLocation(ip) {
  try {
    const response = await axios.get(`http://ip-api.com/json/${ip}?fields=status,message,query,country,regionName,city,zip,lat,lon,timezone,isp`);
    return response.data;
  } catch (error) {
    console.error('Error fetching IP geo location:', error.message);
    return null;
  }
}

// 英文->中文
async function translateTextToChinese(text) {
    try {
      // 将文本翻译成中文
      const result = await translate(text, { to: 'zh-CN' });
      return result;
    } catch (error) {
      console.error('Error translating text:', error.message);
      return null;
    }
}

//操作日志
router.get('/getvalue',async(req,res)=>{
  let ipAddress = await getPublicIP();
  let geoLocation = await getIPGeoLocation(ipAddress);
  res.send({value:geoLocation.city})
})
router.post("/addOperation", async (req, res) => {
    try {
        let ipAddress = await getPublicIP();
        if (!ipAddress) {
          return res.status(500).send({ code: 500, message: 'Failed to fetch public IP' });
        }

        let geoLocation = await getIPGeoLocation(ipAddress);
        if (!geoLocation) {
          return res.status(500).send({ code: 500, message: 'Failed to fetch IP geo location' });
        }
        console.log(geoLocation);

        let body = req.body;
        body.newTime = new Date();
        body.address = ipAddress;
        body.homePlace = geoLocation.city;
        
        await operationModel.create(body);

        res.send({ code: 200 });
    } catch (error) {
        console.error('Error processing request:', error.message);
        res.status(500).send({ code: 500, message: 'Internal Server Error' });
    }
});
router.get("/getoperation",async(req,res)=>{
  let {_id,newTime,feature,address,operation,homePlace}=req.query
  let operationList=[]
  let idReg=new RegExp(_id)
  let featureReg=new RegExp(feature)
  let operationReg=new RegExp(operation)
  let addressReg=new RegExp(address)
  let homePlaceReg=new RegExp(homePlace)
  if(_id && newTime && feature && address || homePlace && operation){
    operationList=await operationModel.find({_id:idReg,newTime,feature:featureReg,address:addressReg,operation:operationReg,homePlace:homePlaceReg})
  }else if(_id && newTime && feature && address && operation){
    operationList=await operationModel.find({_id:idReg,newTime,feature:featureReg,address:addressReg,operation:operationReg})
  }else if(_id  && newTime && feature && address){
    operationList=await operationModel.find({_id:idReg,newTime,feature:featureReg,address:addressReg})
  }else if(_id  && newTime && feature){
    operationList=await operationModel.find({_id:idReg,newTime,feature:featureReg})
  }else if(_id  && newTime){
    operationList=await operationModel.find({_id:idReg,newTime})
  }else if(newTime && feature && address && operation || homePlace){
    operationList=await operationModel.find({newTime,feature:featureReg,address:addressReg,operation:operationReg,homePlace:homePlaceReg})
  }else if(newTime && feature && address && operation){
    operationList=await operationModel.find({newTime,feature:featureReg,address:addressReg,operation:operationReg})
  }else if(newTime && feature && address){
    operationList=await operationModel.find({newTime,feature:featureReg,address:addressReg})
  }else if(newTime && feature){
    operationList=await operationModel.find({newTime,feature:featureReg})
  }else if(feature && address && operation || homePlace){
    operationList=await operationModel.find({feature:featureReg,address:addressReg,operation:operationReg,homePlace:homePlaceReg})
  }else if(feature && address && operation){
    operationList=await operationModel.find({feature:featureReg,address:addressReg,operation:operationReg})
  }else if(feature && address){
    operationList=await operationModel.find({feature:featureReg,address:addressReg})
  }else if(address && operation || homePlace){
    operationList=await operationModel.find({address:addressReg,operation:operationReg,homePlace:homePlaceReg})
  }else if(address && operation){
    operationList=await operationModel.find({address:addressReg,operation:operationReg})
  }else if(address || homePlace){
    operationList=await operationModel.find({address:addressReg,homePlace:homePlaceReg})
  }else if(operation && homePlace){
    operationList=await operationModel.find({operation:operationReg,homePlace:homePlaceReg})
  }else if(_id){
    operationList=await operationModel.find({_id:idReg})
  }else if(newTime){
    operationList=await operationModel.find({newTime})
  }else if(feature){
    operationList=await operationModel.find({feature:featureReg})
  }else if(address){
    operationList=await operationModel.find({address:addressReg})
  }else if(operation){
    operationList=await operationModel.find({operation:operationReg})
  }else if(homePlace){
    operationList=await operationModel.find({homePlace:homePlaceReg})
  }else{
    operationList=await operationModel.find()
  }
  res.send({operationList})
})



// router.get('/getoperation',async(req,res)=>{
//   let query=req.query
//   let operationList=await operationModel.find(query)
//   res.send({operationList})
// })

//map
router.get("/getmap",async(req,res)=>{
  // 定义请求参数
  const parameters = {
    origin: '116.466485,39.995197', // 起点坐标
    destination: '116.46424,40.020642', // 终点坐标
    key: '9786bf9df0d621fdae84f8889d0159d1', 
  };

  // 构建完整的 URL
  const url = `https://restapi.amap.com/v5/direction/electrobike?${new URLSearchParams(parameters)}`;

  axios.get(url)
    .then(response => {
      console.log('Response:', response.data);
    })
    .catch(error => {
      console.error('Error:', error.message);
    });
})

//身份管理
router.post("/addstanding",async(req,res)=>{
    let body=req.body
    body.newTime=new Date()
    await StandingModel.create(body)
    res.send({code:200})
})
router.get("/getstanding",async(req,res)=>{
    let {_id}=req.query
    if(_id){
        let list=await StandingModel.find({_id})
        let item=list.map(result=>result.authority)
        let standingList=await StandingModel.aggregate([
            {
                $match:{authority:{$in:item}}
            },
            {
                $lookup:{
                    from:'authority',
                    localField:'authority',
                    foreignField:'_id',
                    as:'authority'
                }
            }
        ])
        res.send({standingList})
    }else{
        let standingList=await StandingModel.aggregate([
            {
                $lookup:{
                    from:'authority',
                    localField:'authority',
                    foreignField:'_id',
                    as:'authority'
                }
            }
        ])
        res.send({standingList})
    }
    
})
router.put("/editstanding/:_id",async(req,res)=>{
    let _id=req.params._id
    await StandingModel.findByIdAndUpdate(_id,req.body)
    res.send({code:200})
})
router.delete("/delstanding/:_id",async(req,res)=>{
    let _id=req.params._id
    await StandingModel.deleteOne({_id})
    res.send({code:200})
})

//权限管理
router.post("/addauthority",async(req,res)=>{
    await AuthorityModel.create(req.body)
    res.send({code:200})
})
router.get("/getauthority",async(req,res)=>{
    let {idList}=req.query
    let authorityObj={}
    let authorityList=[]

    if (idList) {
        let list = await AuthorityModel.find({ _id: { $in: idList } }).lean();
        list.forEach(item => {
            authorityObj[item._id] = item;
        });
    } else {
        let list = await AuthorityModel.find().lean();
        list.forEach(item => {
            authorityObj[item._id] = item;
        });
    }

    Object.values(authorityObj).forEach(item => {
        if (!item['authorityId']) {
            authorityList.push(item);
        } else {
            if (authorityObj[item['authorityId']]) { // 添加检查以确保 authorityObj[item['authorityId']] 存在
                if (!authorityObj[item['authorityId']]['children']) {
                    authorityObj[item['authorityId']]['children'] = [];
                }
                authorityObj[item['authorityId']]['children'].push(item);
            } else {
                console.error(`Missing parent for authorityId: ${item['authorityId']}`);
            }
        }
    });
    res.send({ authorityList });
    
})
router.put("/editauthority/:_id",async(req,res)=>{
    let _id=req.params._id
    await AuthorityModel.findByIdAndUpdate(_id,req.body)
    res.send({code:200})
})
router.delete("/delauthority/:_id",async(req,res)=>{
    let _id=req.params._id
    await AuthorityModel.deleteOne({_id})
    res.send({code:200})
})

// 添加商家店铺
router.post("/addBusiness", async (req, res) => {
  const count = await BusinessModel.countDocuments();
  try {
    await BusinessModel.create({ ...req.body, store_id: count + 1 });
    res.send({ code: 200, msg: "创建成功" });
  } catch (error) {
    res.status(500).send({ msg: "服务器错误", error: error.message });
  }
})
// 添加骑手信息
router.post("/addDelivery", async (req, res) => {
  const count = await DeliveryModel.countDocuments();
  try {
    await DeliveryModel.create({ ...req.body, rider_id: count + 1 })
    res.send({ code: 200, msg: "创建成功" });
  } catch (error) {
    res.status(500).send({ msg: "服务器错误", error: error.message });
  }
})
// 获取外卖员信息
// router.get("/getRider", async (req, res) => {
//   try {
//     const data = await DeliveryModel.find();
//     res.send({ code: 200, msg: "获取成功", data });
//   } catch (error) {
//     res.status(500).send({ msg: "服务器错误", error: error.message });
//   }
// })
// 添加买家信息
router.post("/addBuyer", async (req, res) => {
  // 计算当前买家数据长度
  let count = await BuyerModel.countDocuments();
  try {
    await BuyerModel.create({ ...req.body, buyer_id: count + 1 })
    res.send({ code: 200, msg: "创建成功" });
  } catch (error) {
    res.status(500).send({ msg: "服务器错误", error: error.message });
  }
})
// 新增订单
router.post("/addOrder", async (req, res) => {
  const count = await OrderModel.countDocuments();
  const { buyer_id, store_id } = req.body;
  // BuyerModel,使用buyer_id查询用户地址
  let buyer = await BuyerModel.findOne({ buyer_id });
  // BusinessModel，使用store_id查询商家地址
  let business = await BusinessModel.findOne({ store_id });
  // 经过前端传递过来的用户id和商家id来获取地址
  try {
    await OrderModel.create({ ...req.body, order_id: count + 1, order_pickupLocation: buyer.buyer_harvest_address, order_deliveryLocation: business.store_address })
    res.send({ code: 200, msg: "创建成功" });
  } catch (error) {
    res.status(500).send({ msg: "服务器错误", error: error.message });
  }
})
// 获取订单信息
router.get("/getOrder", async (req, res) => {
  let obj = req.query;
  const { page, pagesize } = obj
  try {
    // 聚合查询之后按照order_exception_status字段进行排序，辅助排序字段为order_sales_status
    let data = await OrderModel.aggregate([
      {
        $lookup: {
          from: "business",
          localField: "store_id",
          foreignField: "store_id",
          as: "business"
        }
      },
      {
        $lookup: {
          from: "buyer",
          localField: "buyer_id",
          foreignField: "buyer_id",
          as: "buyer"
        }
      },
      {
        $lookup: {
          from: "delivery",
          localField: "rider_id",
          foreignField: "rider_id",
          as: "delivery"
        }
      },
      {
        $sort: {
          order_exception_status: -1, // 升序排序
          order_sales_status: -1      // 如果order_exception_status相同，则按此字段升序排序
        }
      }
    ]);
    // 动态构建筛选条件  备注，勿删
    // let filteredData = data.filter(order => {
    //   // 直接遍历这个对象来查看这个对象的属性值
    //   for (let key in obj) {
    //     // 检查对象是否具有这个属性
    //     // console.log(key);
    //     if (obj.hasOwnProperty(key)) {
    //       let value = obj[key];
    //       // 如果属性值不为空，则进行匹配
    //       if (value) {
    //         if (key === '_id') {
    //           console.log('id');
    //           if (order._id.toString() !== value) {
    //             return false;
    //           }
    //         }
    //         // 判断订单列表中是否有订单的名称和商品名称包含搜索关键词
    //         if (key === "goodsname") {
    //           console.log('goodsname');
    //           if (!order.order_product_list.some(good => good.goodsname.includes(value))) {
    //             return false;
    //           }
    //         }
    //         // 根据店铺名称shopname来进行筛选
    //         if (key === "shopname") {
    //           console.log('shopname');
    //           if (!order.business[0].store_name.includes(value)) {
    //             return false;
    //           }
    //         }
    //         // 根据买家昵称进行筛选
    //         if (key === "buyname") {
    //           console.log('buyname');
    //           if (!order.buyer[0].buyer_nickname.includes(value)) {
    //             return false;
    //           }
    //         }
    //         // 根据买家人姓名进行筛选
    //         if (key === "receivename") {
    //           console.log('receivename');
    //           if (!order.buyer[0].buyer_name.includes(value)) {
    //             return false;
    //           }
    //         }
    //         // 根据骑手姓名进行筛选
    //         if (key === "deliveryname") {
    //           console.log('deliveryname');
    //           if (!(order.delivery.length > 0 && order.delivery[0].rider_name.includes(value))) {
    //             return false;
    //           }
    //         }
    //         // 根据手机号码进行搜索
    //         if (key === "phonenumber") {
    //           console.log('phonenumber');
    //           if (
    //             !(order.buyer[0].buyer_phone.includes(value) ||
    //             order.delivery.length > 0 && order.delivery[0].rider_phone.includes(value) ||
    //             order.business[0].store_phone.includes(value))
    //           ) {
    //             return false;
    //           }
    //         }
    //         // 根据订单创建事件进行搜索
    //         if (key === "createtime") {
    //           console.log('createtime');
    //           // 如果对应的值为0，则不进行筛选，
    //           // 如果对应的值为1，则筛选出来本月订单，
    //           // 如果对应的值为2，则筛选出来近三个月订单，
    //           // 如果对应的值为3，则筛选出来今年内订单，
    //           // 如果对应的值为4，则筛选出来2021年订单，
    //           // 如果对应的值为5，则筛选出来2020年订单，
    //           // 如果对应的值为6，则筛选出来2020年以前的订单，
    //           if (value == "0") {
    //             return true;
    //           }
    //           if (value == "1") {
    //             // 获取当前时间
    //             let now = new Date();
    //             // 获取当前月份
    //             let month = now.getMonth() + 1;
    //             // 获取当前年份
    //             let year = now.getFullYear();
    //             // 获取当前月份的第一天
    //             let firstDay = new Date(year, month - 1, 1);
    //             // 获取当前月份的最后一天
    //             let lastDay = new Date(year, month, 0);
    //             if (order.order_create_time >= firstDay && order.order_create_time <= lastDay) {
    //               return true;
    //             } else {
    //               return false;
    //             }
    //           }
    //           if (value == "2") {
    //             return (order.order_create_time >= new Date(year - 1, month - 1, 1) && order.order_create_time <= new Date(year - 1, month, 0)) || (order.order_create_time >= new Date(year - 2, month - 1, 1) && order.order_create_time <= new Date(year - 2, month, 0));
    //           }
    //           if (value == "3") {
    //             return order.order_create_time >= new Date(year - 1, month - 1, 1) && order.order_create_time <= new Date(year - 1, month, 0);
    //           }
    //           if (value == "4") {
    //             return order.order_create_time >= new Date(year - 2, month - 1, 1) && order.order_create_time <= new Date(year - 2, month, 0);
    //           }
    //           if (value == "5") {
    //             return order.order_create_time >= new Date(year - 3, month - 1, 1) && order.order_create_time <= new Date(year - 3, month, 0);
    //           }
    //           if (value == "6") {
    //             return order.order_create_time < new Date(year - 3, month - 1, 1);
    //           }
    //         }
    //         // 根据配送状态来进行搜索
    //         if (key === "delivery_status") {
    //           console.log("delivery_status");
    //           // 如果值为0，则不进行筛选，
    //           // 如果值为1，则筛选出待接单订单，
    //           // 如果值为2，则筛选出配送中订单，
    //           // 如果值为3，则筛选出配送成功订单，
    //           if (value == "0") {
    //             return true;
    //           } else if (value == "1") {
    //             return order.order_delivery_status == 1;
    //           } else if (value == "2") {
    //             return order.order_delivery_status == 2;
    //           } else if (value == "3") {
    //             return order.order_delivery_status == 3;
    //           } 
    //         }
    //         // 根据配送异常状态来进行搜索
    //         if (key === "exception_status") {
    //           console.log("exception_status");
    //           // 如果值为0，则不进行筛选，
    //           // 如果值为1，则筛选出order_exception_status值为1的订单，
    //           // 如果值为2，则筛选出order_exception_status值为2的订单，
    //           // 如果值为3，则筛选出order_exception_status值为3的订单，
    //           // 如果值为4，则筛选出order_exception_status值为4的订单，
    //           // 如果值为5，则筛选出order_exception_status值为5的订单，
    //           if (value == "0") {
    //             return true;
    //           } else if (value == "1") {
    //             return order.order_exception_status == 1;
    //           } else if (value == "2") {
    //             return order.order_exception_status == 2;
    //           } else if (value == "3") {
    //             return order.order_exception_status == 3;
    //           } else if(value == "4") {
    //             return order.order_exception_status == 4;
    //           }else if (value == "5") {
    //             return order.order_exception_status == 5;
    //           }


    //         }
    //         // 根据交易状态来进行搜索
    //         if (key === "transaction_status") {
    //           console.log("transaction_status");
    //           // 如果值为6，则不进行筛选，
    //           // 如果值为1，则筛选出order_transaction_status值为1的订单，
    //           // 如果值为2，则筛选出order_transaction_status值为2的订单，
    //           if(value == "6"){
    //             return true;
    //           }
    //           if (value == "1") {
    //             return order.order_transaction_status == 1;
    //           } else if (value == "2") {
    //             return order.order_transaction_status == 2;
    //           }
    //         }

    //       }
    //     }
    //   }
    //   return true;
    // });
    let filteredData = data.filter(order => {
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          let value = obj[key];
          if (value) {
            if (key === '_id') {
              if (order._id.toString() !== value) {
                return false;
              }
            } else if (key === "goodsname") {
              if (!order.order_product_list.some(good => good.goodsname.includes(value))) {
                return false;
              }
            } else if (key === "shopname") {
              if (!order.business[0].store_name.includes(value)) {
                return false;
              }
            } else if (key === "buyname") {
              if (!order.buyer[0].buyer_nickname.includes(value)) {
                return false;
              }
            } else if (key === "receivename") {
              if (!order.buyer[0].buyer_name.includes(value)) {
                return false;
              }
            } else if (key === "deliveryname") {
              if (!(order.delivery.length > 0 && order.delivery[0].rider_name.includes(value))) {
                return false;
              }
            } else if (key === "phonenumber") {
              if (
                !(
                  order.buyer[0].buyer_phone.includes(value) ||
                  (order.delivery.length > 0 && order.delivery[0].rider_phone.includes(value)) ||
                  order.business[0].store_phone.includes(value)
                )
              ) {
                return false;
              }
            } else if (key === "createtime") {
              let now = new Date();
              let month = now.getMonth(); // 注意月份是从0开始的
              let year = now.getFullYear();
              let firstDay, lastDay;

              switch (value) {
                case "0":
                  continue; // 不进行筛选
                case "1":
                  firstDay = new Date(year, month, 1); // 当前月份的第一天
                  lastDay = new Date(year, month + 1, 0); // 当前月份的最后一天
                  break;
                case "2":
                  firstDay = new Date(year, month - 2, 1); // 近三个月的第一天
                  lastDay = new Date(); // 当前日期
                  break;
                case "3":
                  firstDay = new Date(year, 0, 1); // 今年的第一天
                  lastDay = new Date(); // 当前日期
                  break;
                case "4":
                  firstDay = new Date(2021, 0, 1); // 2021年的第一天
                  lastDay = new Date(2021, 11, 31); // 2021年的最后一天
                  break;
                case "5":
                  firstDay = new Date(2020, 0, 1); // 2020年的第一天
                  lastDay = new Date(2020, 11, 31); // 2020年的最后一天
                  break;
                case "6":
                  firstDay = new Date(1970, 0, 1); // 1970年的第一天
                  lastDay = new Date(2019, 11, 31); // 2019年的最后一天
                  break;
                default:
                  return false; // 如果`value`不是预期的值，则直接排除
              }

              if (firstDay && lastDay) {
                if (order.order_create_time < firstDay || order.order_create_time > lastDay) {
                  return false;
                }
              }
            } else if (key === "delivery_status") {
              if (value != "0" && order.order_delivery_status != value) {
                return false;
              }
            } else if (key === "exception_status") {
              if (value != "0" && order.order_exception_status != value) {
                return false;
              }
            } else if (key === "transaction_status") {
              if (value != "0" && order.order_transaction_status != value) {
                return false;
              }
            }
          }
        }
      }
      return true; // 如果所有的条件都未触发，则保留该订单
    });
    // 计算一下订单总数
    let total = filteredData.length;
    // filteredData根据page,pagesize进行分页
    filteredData = filteredData.slice(
      (page - 1) * pagesize,
      page * pagesize
    );
    res.send({ code: 200, msg: "获取成功", data: filteredData, total });
  } catch (error) {
    res.status(500).send({ msg: "服务器错误", error: error.message });
  }
});
// 获取订单异常订单条数和历史条数
router.get("/getOrders", async (req, res) => {
  let deliveryorderNum = await OrderModel.countDocuments({ order_exception_status: { $in: [1, 2, 3, 4, 5] } });
  // console.log(deliveryorderNum);
  let historyorderNum = await OrderModel.countDocuments({});
  // console.log(historyorderNum);
  res.send({ code: 200, msg: "获取成功", deliveryorderNum, historyorderNum });

})
// 更改订单信息
// router.post("/updateOrder", async (req, res) => {
//   console.log(req.body);

// })

// 创建socket服务器
const { Server } = require("socket.io");
const io = new Server(3100, {
  // 允许跨域
  cors: {
    origin: "*",
  },
});
io.on("connection", (socket) => {
  console.log("用户连接成功");
  socket.on("sendMsg", (data) => {
    console.log(data);
    // 发送给除了自己以外的客户端
    socket.broadcast.emit("receiveMsg", data);
  });
});



module.exports = router;